package br.com.onlinebidding.mb;

import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import br.com.onlinebidding.facade.UserFacade;
import br.com.onlinebidding.model.User;

@SessionScoped
@ManagedBean(name = "userMB")
public class UserMB extends AbstractMB implements Serializable {

	public static final String INJECTION_NAME = "#{userMB}";
	private static final long serialVersionUID = 1L;

	private User user;
	private List<User> users;
	private UserFacade userFacade;
	private User userLogged;

	public UserFacade getUserTFacade() {
		if (this.userFacade == null) {
			this.userFacade = new UserFacade();
		}

		return this.userFacade;
	}

	public void insertUser() {
		try {
			getUserTFacade().insertUser(this.user);
			closeDialog();
			displayInfoMessageTo("Inserido Com Sucesso!");
			loadUsers();
			resetUser();
		} catch (Exception e) {
			keepDialogOpen();
			displayErrorMessageTo("Ops, erro ao inserir . Tente novamente mais tarde!");
			e.printStackTrace();
		}
	}

	public void updateUser() {
		try {
			getUserTFacade().updateUser(this.user);
			closeDialog();
			displayInfoMessageTo("Alterado Com Sucesso!");
			loadUsers();
			resetUser();
		} catch (Exception e) {
			keepDialogOpen();
			displayErrorMessageTo("Ops, erro ao alterar . Tente novamente mais tarde!");
			e.printStackTrace();
		}
	}

	public void deleteUser() {
		try {
			getUserTFacade().deleteUser(this.user);
			closeDialog();
			displayInfoMessageTo("Excluido Com Sucesso!");
			loadUsers();
			resetUser();
		} catch (Exception e) {
			keepDialogOpen();
			displayErrorMessageTo("Ops, erro ao excluir  . Tente novamente mais tarde!");
			e.printStackTrace();
		}
	}

	public List<User> getAllUsers() {
		if (this.users == null) {
			loadUsers();
		}

		return this.users;
	}

	public List<User> getUsers() {
		return this.users;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}

	private void loadUsers() {
		this.users = getUserTFacade().listAll();
	}

	public void resetUser() {
		this.user = new User();
	}

	public String logOut() {
		getRequest().getSession().invalidate();
		return "/view/public/login.xhtml";
	}

	private HttpServletRequest getRequest() {
		return (HttpServletRequest) FacesContext.getCurrentInstance()
				.getExternalContext().getRequest();
	}

	public User getUserLogged() {
		return userLogged;
	}

	public void setUserLogged(User userLogged) {
		this.userLogged = userLogged;
	}

	public boolean isAdmin() {
		return userLogged.isAdmin();
	}

	public boolean isDefaultUser() {
		return userLogged.isUser();
	}

	public User getUser() {
		return this.user;
	}

	public void setUser(User user) {
		this.user = user;
	}

}